from flask import Flask, make_response, jsonify, g, current_app as app,Blueprint,request
from sqlalchemy import select,insert,update,func,join
from sqlalchemy.sql import text
from eim.tools.dbtool import DBTool
from eim import db
from eim.tools.searchtool import SearchCondition,SearchConditionList,MatchLogic,PartnerRS
from eim.result.simple_result import SimpleResult

narule=Blueprint("narule","narule",__name__,url_prefix="/narule")

@narule.route("/append",methods=["PUT"])
def appeneNewRule():
    """
    增加一个新的网络日志分析规则
    """
    try:
        res = request.json
        if(not isinstance(res,dict)):
            raise Exception("日志分析规则的参数必须为json格式")
        ks = res.keys()
        if (not "mainre"  in ks):
            raise Exception("缺少主识别正则")
        
        if (not "devicename"  in ks):
            raise Exception("缺少设备种类")
        
        if (not "precode_re"  in ks):
            raise Exception("缺少前导符的正则表达式")
                
        if (not "createtime_re"  in ks):
            raise Exception("缺少日志生成时间正则表达式")
                
        if (not "hostname_re"  in ks):
            raise Exception("缺少主机名称的正则表达式")
                
        if (not "logversion_re"  in ks):
            raise Exception("缺少日志版本正则表达式")
                
        if (not "logversion_re"  in ks):
            raise Exception("缺少日志版本正则表达式")
                
        if (not "logversion_re"  in ks):
            raise Exception("缺少日志版本正则表达式")
                
        if (not "serverity_re"  in ks):
            raise Exception("缺少日志级别正则")
        
        if (not "brief_re"  in ks):
            raise Exception("缺少摘要信息正则")
        
        if (not "infotype_re"  in ks):
            raise Exception("缺少信息类别正则")
        
        if (not "serialno_re"  in ks):
            raise Exception("缺少顺序码正则")
        
        if (not "description_re"  in ks):
            raise Exception("缺少详细信息正则")
        
        from eim.Services.netanalysisrule import NetAnalysisRule
        nal = NetAnalysisRule(db)
        id = nal.appendNewRule(res)
        return SimpleResult(status="T",value=id).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()
    
@narule.route("/getrunrule",methods=["GET"])
def getRunRule():
    """
    获取正在运行的网络日志分析规则
    """
    try:
        from eim.Services.netanalysisrule import NetAnalysisRule
        nal = NetAnalysisRule(db)
        res = nal.getRunRule()
        return SimpleResult(status='T',value=res).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()